package quickdb.db.connection;

import java.sql.ResultSet;
import java.sql.SQLException;

/** Represents an SQLite database. 
 * 
 * @author Hans de Ruiter
 *
 */
public class ConnectionDBSQLite extends ConnectionDB {

	public ConnectionDBSQLite(String... dbParameters) throws ClassNotFoundException {
        super(dbParameters);
        this.driver = "org.sqlite.JDBC";
        this.url = "jdbc:sqlite:" + nameDB + ".db";
        Class.forName(this.driver);
	}
	
    @Override
    public void openBlock(String tableName) throws SQLException{
        try {
            statement = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY,
                    ResultSet.CONCUR_UPDATABLE);
            rs = statement.executeQuery("SELECT * FROM " + tableName + ";");
            rs.moveToInsertRow();
            tryAgain = true;
        } catch (SQLException e) {
            if (tryAgain) {
                this.connect();
                tryAgain = false;
                this.openBlock(tableName);
            } else {
            	throw e;
            }
        }
    }
    
    @Override
    public boolean existTable(String tableName) throws SQLException {
        statement = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY,
                ResultSet.CONCUR_READ_ONLY);
        try {
        	rs = statement.executeQuery("SELECT * FROM " + tableName + " LIMIT 1;");
        } catch (SQLException e) {
        	// Failure means no table
        	return false;
        }
        return rs.next();
    }

    @Override
    public ResultSet updateField(String table, String where) throws SQLException {
        try {
            statement = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY,
                    ResultSet.CONCUR_UPDATABLE);
            rs = statement.executeQuery("SELECT * FROM " + table + " WHERE " + where + ";");
            tryAgain = true;
        } catch (SQLException e) {
            if (tryAgain) {
                this.connect();
                tryAgain = false;
                return this.updateField(table, where);
            } else {
            	throw e;
            }
        }
        return rs;
    }
}
